package com.moleq.adapter;

import java.util.List;

import com.moleq.mgpos.widget.BeepButton;
import com.moleq.models.FreeFunction;
import com.moleq.models.FunctionPanel;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;

public class FuncSelectionAdapter extends BaseAdapter {

	private Context mContext;
	private List<FunctionPanel> dataSource;
	private OnClickListener mOnClickListener;

	private static final int btnId = 0x12345678;
	private static final String TAG = "inner FuncSelectionAdapter ";

	public FuncSelectionAdapter(Context context, List<FunctionPanel> data) {

		this.mContext = context;
		this.dataSource = data;

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return dataSource.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return dataSource.get(arg0);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View rowView = convertView;
		Holder holder = null;
		if (rowView == null) {
			holder = new Holder();
			rowView = createFuncView();
			holder.button = (Button) rowView.findViewById(btnId);
			rowView.setTag(holder);
		} else {
			holder = (Holder) rowView.getTag();
		}

		if (holder != null) {
			holder.setDisplayData(dataSource.get(position));
		}

		return rowView;
	}

	class Holder {
		Button button;

		public void setDisplayData(FunctionPanel obj) {

			if (obj != null) {

				if (obj.getTp_func_key() == 0) {
					button.setVisibility(View.INVISIBLE);
				} else {
					button.setVisibility(View.VISIBLE);
				}
				button.setText(obj.getDisplayText());
				Drawable leftDrawable;
				leftDrawable = mContext.getResources().getDrawable(obj.getIconId());
				// user setCompoundDrawables() method , you must call
				// Drawable.setBounds() method !Or the Image can't show .
				leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
				button.setCompoundDrawables(leftDrawable, null, null, null);
				button.setTag(obj);
			}

		}
	}

	private View createFuncView() {

		LinearLayout layout = new LinearLayout(mContext);
		BeepButton funcView = new BeepButton(mContext);
		funcView.setId(btnId);
		funcView.setWidth(190);
		funcView.setHeight(60);
		if (mOnClickListener != null) {
			funcView.setOnClickListener(mOnClickListener);
		}
		layout.addView(funcView);

		return layout;

	}

	public void setOnItemClicklistener(OnClickListener listener) {
		this.mOnClickListener = listener;
	}

}
